import { defineStore } from 'pinia'
import useStore from '@renderer/pinai/modules/user'
import { getOfflineMsgApi } from '@renderer/api/chat'

const useChat = defineStore('useChat', {
  state: () => ({
    // 会话列表
    sessionChatList: [] as any[],
    // 当前会话的id
    currendSessionId: 0,
    // 和当前聊天对象的消息列表
    messageList: [] as any[]
  }),
  actions: {
    // 初始化会话列表
    initSessionChatList() {
      const userStore = useStore()
      this.sessionChatList = JSON.parse(
        localStorage.getItem(`chatlist_${userStore.userInfo.id}`) || '[]'
      )
    },
    // 添加会话
    addSessionChatList(chat: any) {
      const userStore = useStore()
      this.sessionChatList = JSON.parse(
        localStorage.getItem(`chatlist_${userStore.userInfo.id}`) || '[]'
      )
      const index = this.sessionChatList.findIndex(
        (item) => item.id == chat[0].id
      )
      if (index === -1) {
        this.sessionChatList.push(chat[0])
        for (let i = 0; i < this.sessionChatList.length; i++) {
          if (this.sessionChatList[i].id == this.currendSessionId) {
            this.sessionChatList[i].noreadnum = 0
          }
        }
      } else {
        this.sessionChatList.splice(index, 1, chat[0])
        for (let i = 0; i < this.sessionChatList.length; i++) {
          if (this.sessionChatList[i].id == this.currendSessionId) {
            this.sessionChatList[i].noreadnum = 0
          }
        }
      }
      //  存储
      const key = `chatlist_${userStore.userInfo.id}`
      localStorage.setItem(key, JSON.stringify(this.sessionChatList))
    },
    // 清空未读消息
    clearNoReadNum(id: number | string) {
      const userStore = useStore()
      for (let i = 0; i < this.sessionChatList.length; i++) {
        if (this.sessionChatList[i].id == id) {
          this.sessionChatList[i].noreadnum = 0
        }
      }
      const key = `chatlist_${userStore.userInfo.id}`
      localStorage.setItem(key, JSON.stringify(this.sessionChatList))
    },
    // 设置当前对话的id
    setCurrentSessionId(id: number) {
      this.currendSessionId = id
    },
    // 获得当前聊天对象的消息列表
    getMessageList(user_id, friend_id, type = 'user') {
      const key = `chatDetail_${user_id}_${type}_${friend_id}`
      this.messageList = JSON.parse(localStorage.getItem(key) || '[]')
    },
    // 获得离线消息
    getOfflineMessage() {
      getOfflineMsgApi().then(() => {
        console.log('获取离线消息')
      })
    }
  }
})

export default useChat
